package com.sfdk.resources {
    import com.sfdk.events.IOEvent;
    import com.sfdk.events.ResourcesEvent;
    import com.sfdk.graphics.api.ILoadingBar;
    import com.sfdk.io.GenericIO;
    import com.sfdk.io.data.URLObject;

    import flash.utils.getDefinitionByName;

    public class ResourcesLoader extends GenericIO {
        private var _loadingBar:ILoadingBar;

        private var _resourcesToLoad:int;
        private var _resourcesLoaded:int;

        public function ResourcesLoader(loadingBar:ILoadingBar = null) {
            _loadingBar = loadingBar;

            super("config/resources.xml");
        }

        override protected function init():void {
            var xmlResource:XML = getFileData();
            var urls:Vector.<URLObject> = getUrls(xmlResource);
            _resourcesToLoad = urls.length;
            _resourcesLoaded = 0;

            var i:int = 0;
            var type:String;
            var classToUse:Class;
            var newObj:GenericIO;
            for (i; i < _resourcesToLoad; i++) {
                type = urls[i].type;
                classToUse = getDefinitionByName(type) as Class;
                newObj = new classToUse(urls[i].url);
                newObj.addEventListener(IOEvent.LOAD_COMPLETE, onResourceLoaded);
            }
        }

        private function getUrls(xmlResource:XML):Vector.<URLObject> {
            var elementList:XMLList = xmlResource.elements("element");
            var urls:Vector.<URLObject> = new Vector.<URLObject>();
            var url:String = "";
            var event:String = "";
            var type:String = "";
            for (var i:int = 0; i < elementList.length(); i++) {
                url = elementList[i].url;
                event = elementList[i].event;
                type = elementList[i].type;
                urls.push(new URLObject(url, event, type));
            }
            return urls;
        }

        private function onResourceLoaded(e:IOEvent):void {
            _resourcesLoaded++;
            if (_loadingBar != null) {
                _loadingBar.setValue(int(_resourcesLoaded / _resourcesToLoad))
            }
            if (_resourcesLoaded == _resourcesToLoad) {
                dispatchEvent(new ResourcesEvent(ResourcesEvent.RESOURCES_LOADED))
                _loadingBar = null;
            }
        }
    }
}